package com.test.appotasdk;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import android.app.Activity;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Typeface;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.TextView;
import android.widget.Toast;

import com.appota.asdk.callback.AppotaReceiver;
import com.appota.asdk.callback.LoginFacebookCallback;
import com.appota.asdk.callback.UserInfoCallback;
import com.appota.asdk.commons.AccessTokenUtil;
import com.appota.asdk.commons.Constants;
import com.appota.asdk.items.ItemAPI;
import com.appota.asdk.model.AppotaAccessToken;
import com.appota.asdk.model.ItemTransactionInfo;
import com.appota.asdk.model.TransactionInfo;
import com.appota.asdk.model.TransactionResult;
import com.appota.asdk.topup.TopupAPI;
import com.appota.asdk.user.AppotaUser;
import com.appota.asdk.user.UserAPI;
import com.facebook.FacebookException;
import com.facebook.Session;
import com.facebook.SessionState;
import com.facebook.widget.LoginButton;
import com.facebook.widget.LoginButton.OnErrorListener;

public class PayActivity extends Activity {
	
	private TopupAPI topupAPI;
	private ItemAPI itemAPI;
	private UserAPI userAPI;
	private Typeface tf;
	private MyReceiver receiver;
	private LoginButton btnFacebook;
	private Session.StatusCallback callback = new FacebookSessionStatusCallback();

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.layout_pay);
		topupAPI = TopupAPI.getInstance().setContext(this);
		itemAPI = ItemAPI.getInstance().setContext(this);
		userAPI = UserAPI.getInstance().setContext(this);
		tf = Typeface.createFromAsset(getAssets(), "font/UVNBanhMi.TTF");
		receiver = new MyReceiver();
		IntentFilter filter = new IntentFilter();
		filter.addAction(Constants.LOGIN_ACTION);
		filter.addAction(Constants.BUYITEM_ACTON);
		filter.addAction(Constants.LIST_ITEM_ACTON);
		filter.addAction(Constants.TOPUP_TYM_ACTION);
		filter.addAction(Constants.INAPP_BANK_ACTION);
		filter.addAction(Constants.INAPP_CARD_ACTION);
		filter.addAction(Constants.INAPP_PAYPAL_ACTION);
		filter.addAction(Constants.INAPP_SMS_ACTION);
		registerReceiver(receiver, filter);
		getUserInfo();
		findViewById(R.id.btn_buymore).setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				Intent i = new Intent(PayActivity.this, PaymentChooserActivity.class);
				startActivity(i);
				//topupTYM();
			}
		});
		
		findViewById(R.id.btn_appota).setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				getItemList();
			}
		});
		
		findViewById(R.id.btn_play).setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				topupTYM();
			}
		});
		btnFacebook = (LoginButton) findViewById(R.id.btn_facebook);
		btnFacebook.setOnErrorListener(new OnErrorListener() {
			@Override
			public void onError(FacebookException error) {
				// TODO Auto-generated method stub
				System.err.println(error.getMessage());
			}
		});
		btnFacebook.setReadPermissions(Arrays.asList("basic_info", "email"));
		btnFacebook.setSessionStatusCallback(callback);
	}

	private void topupTYM(){
		List<String> scopes = new ArrayList<String>();
		scopes.add(Constants.USER_INFO_SCOPE);
		scopes.add(Constants.INAPP_SCOPE);
		scopes.add(Constants.USER_CHARGE_SCOPE);
		scopes.add(Constants.USER_PAYMENT_SCOPE);
		topupAPI.topupTYM(scopes, "");
	}
	
	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		unregisterReceiver(receiver);
	}
	
	private void getItemList(){
		String accessToken = AccessTokenUtil.getInstance().init(this).getSavedAccessToken();
		System.err.println("getItem: " + accessToken);
		List<String> scopes = new ArrayList<String>();
		scopes.add(Constants.USER_INFO_SCOPE);
		scopes.add(Constants.INAPP_SCOPE);
		scopes.add(Constants.USER_CHARGE_SCOPE);
		scopes.add(Constants.USER_PAYMENT_SCOPE);
		itemAPI.getItemList(accessToken, scopes, 0, 1, "");
	}
	
	private void getUserInfo(){
		String accessToken = AccessTokenUtil.getInstance().init(this).getSavedAccessToken();
		if(TextUtils.isEmpty(accessToken)){
			return;
		}
		userAPI.getUserInfo(accessToken, new UserInfoCallback() {
			
			@Override
			public void onGetUserInfoSuccess(AppotaUser user) {
				// TODO Auto-generated method stub
				((TextView)findViewById(R.id.money)).setText(user.getTym() + "");
				((TextView)findViewById(R.id.money)).setTypeface(tf);
				((TextView)findViewById(R.id.username)).setText(user.getUserName());
				((TextView)findViewById(R.id.username)).setTypeface(tf);
			}
			
			@Override
			public void onGetUserInfoError(int errorCode) {
				// TODO Auto-generated method stub
				Toast.makeText(PayActivity.this, "Error Code: " + errorCode, Toast.LENGTH_SHORT).show();
			}
		});
	}
	
	@Override
	 public void onActivityResult(int requestCode, int resultCode, Intent data) {
	     super.onActivityResult(requestCode, resultCode, data);
	     Session.getActiveSession().onActivityResult(this, requestCode, resultCode, data);
	 }
	
	private class MyReceiver extends AppotaReceiver {

		@Override
		public void onInAppTransactionSuccess(TransactionResult trans) {
			// TODO Auto-generated method stub
			AlertDialogManager.showPositiveDialog(PayActivity.this, trans.getMessage(), "Type: " + trans.getType() + "\n" + "Amount: " + trans.getAmount() + "\n" + "Currency: " + trans.getCurrency());
		}

		@Override
		public void onInAppTransactionFail(int errorCode, String message) {
			// TODO Auto-generated method stub
			AlertDialogManager.showPositiveDialog(PayActivity.this, message, message + ". ErrorCode: " + errorCode);
		}

		@Override
		public void onBuyItemSuccess(ItemTransactionInfo info, String transactionId) {
			// TODO Auto-generated method stub
			AlertDialogManager.showPositiveDialog(PayActivity.this, info.getMessage(), "Item: " + info.getItemName() + "\nUser: " + info.getUserName() + "\n" + "TYM: " + info.getTotalTYM() + "\n" + "Quantity: " + info.getTotalItem() + "\nTime: " + info.getTime());
		}

		@Override
		public void onBuyItemFail(int errorCode, String message) {
			// TODO Auto-generated method stub
			AlertDialogManager.showPositiveDialog(PayActivity.this, message, message + ". ErrorCode: " + errorCode);
		}

		@Override
		public void onTopupTYMSuccess(TransactionInfo info) {
			// TODO Auto-generated method stub
			
		}

		@Override
		public void onTopupTYMFail(int errorCode, String message) {
			// TODO Auto-generated method stub
			
		}
		
	}
	
	private class FacebookSessionStatusCallback implements Session.StatusCallback {

		@Override
		public void call(final Session session, SessionState state, Exception exception) {
			// TODO Auto-generated method stub
			if(session.isOpened()){
				userAPI.loginWithFacebook(session.getAccessToken(), new LoginFacebookCallback() {
					
					@Override
					public void onLoginFacebookSuccess(AppotaAccessToken accessToken) {
						// TODO Auto-generated method stub
						Toast.makeText(PayActivity.this, "Logged in: " + accessToken.getAccessToken(), Toast.LENGTH_SHORT).show();
					}
					
					@Override
					public void onLoginFacebookFail(String message) {
						// TODO Auto-generated method stub
						Toast.makeText(PayActivity.this, message, Toast.LENGTH_SHORT).show();
					}
				});
			}
		}
	}
}
